package com.kit.personalkit.controller;

import com.kit.personalkit.pojo.dto.ImgDTO;
import com.kit.personalkit.common.JsonResponseBody;
import com.kit.personalkit.mapper.ImageMapper;
import com.kit.personalkit.pojo.entity.Image;
import com.kit.personalkit.tool.ImageCompress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/image")
public class ImageController {

    @Value("${staticPath}")
    private String filePath;

    @Autowired
    private ImageMapper mapper;

    //上传图片
    @RequestMapping("/upload")
    public JsonResponseBody upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        System.out.println("图片原名："+fileName);
        System.out.println("图片大小："+file.getSize()/1024+"kb");

        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;

        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = f.format(new Date());
        File dirFile = new File(filePath + datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        file.transferTo(new File(filePath + datePath + fileName));

        Image image = new Image();
        image.setImage_name(file.getOriginalFilename());
        image.setImage_path(datePath + fileName);
        image.setUpload_time(new Date());
        image.setImage_size(file.getSize());
        mapper.insert(image);

        return JsonResponseBody.ok(datePath + fileName);
    }

    //图片压缩
    @RequestMapping("/compress")
    public JsonResponseBody compress(@RequestBody ImgDTO imgDTO) throws IOException {

        File inputFile = new File(filePath + imgDTO.getUrl());
        //生成一个新名字给压缩后的图片
        String suffix = imgDTO.getUrl().substring(imgDTO.getUrl().lastIndexOf("."));
        System.out.println("图片格式："+suffix);
        String fileName = UUID.randomUUID() + suffix;
        //生成一个日期路径，用于存储压缩后的图片。
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = f.format(new Date());

        File outputFile = new File(filePath+datePath+fileName);
        byte[] inBytes = Files.readAllBytes(inputFile.toPath());

        //实例化一个ImageCompress对象，调用compressPic方法进行图片压缩。将压缩后的字节数据写入输出文件
        ImageCompress imageCompress = new ImageCompress();
        byte[] outBytes = imageCompress.compressPic(inBytes, imgDTO.getSize(), imgDTO.getRatio());

        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            fos.write(outBytes);
        }

        System.out.println("压缩后大小" + outBytes.length / 1024 + "kb");

        //把图片的原本大小和压缩后的大小传给前端
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("originSize", inBytes.length / 1024.0);
        responseMap.put("size", outBytes.length / 1024.0);
        responseMap.put("url", datePath+fileName);

        return JsonResponseBody.ok(responseMap);
    }

    /*下载图片*/
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadImage(@RequestParam("imageUrl") String imageUrl, HttpServletResponse response) throws IOException {
        // 获取对应的图片文件
        File imageFile = new File(filePath+imageUrl);
        if (!imageFile.exists()) {
            throw new RuntimeException("图片文件不存在");
        }
        //获取图片的名字
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")).split("/")[1];
        fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
        //设置响应头和响应内容
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.addHeader("Content-Length", "" + imageFile.length());
        response.setContentType("application/force-download");
        //
        InputStream inputStream = new FileInputStream(imageFile);
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[4096];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
        }
        inputStream.close();
        outputStream.flush();
    }

}

